package com.mytest.provider.rl.test;

import cn.hutool.core.util.IdUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @Author: llq
 * @Date: 2020/5/15
 */
public class ce {
    private static Integer Inventory = 1001;
//    static RedisLockTest redisLockTest = new RedisLockTest();

    public static void main(String[] args) {
        //创建了很多个线程去扣减库存inventory，不出意外的库存扣减顺序变了，最终的结果也是不对的。
        LinkedBlockingQueue queue = new LinkedBlockingQueue<>();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Inventory, Inventory, 10L, SECONDS, queue);
        long start = System.currentTimeMillis();

        RedisLockTest redisLockTest = new RedisLockTest();
        Jedis jedis = new JedisPool("127.0.0.1",6379).getResource();
        LockCase lockCase = new LockCase(jedis,"redis_lock");
        for (int i = 0; i <= 1000; i++) {
            /*threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    RedisLockTest redisLockTest = new RedisLockTest();
                    redisLockTest.lock(UUID.randomUUID().toString());
                    Inventory--;
                    System.out.println(Inventory);
                    redisLockTest.unlock(UUID.randomUUID().toString());

                }
            });*/

            threadPoolExecutor.execute(() -> {
                //通过Snowflake算法获取唯一的ID字符串
                String id = UUID.randomUUID().toString();
                try {
//                    redisLockTest.lock(id);
                    lockCase.lock();
                    Inventory--;
                    System.out.println(Inventory);
                }finally {
//                    redisLockTest.unlock(id);
                    lockCase.unlock();
                }
            });

        }
        long end = System.currentTimeMillis();
        System.out.println("执行线程数 ：" + 1000 + ",总耗时：" + (end - start) + ",库存数:" + Inventory);
    }
}
